package com.huang.servlet;

import com.huang.datebase.UserLog;
import com.huang.info.UserInfo;

import javax.naming.Name;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

/*
	处理登录逻辑
 */
@WebServlet(name = "login", urlPatterns = {"/login"})
public class LoginServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");

		//创建session
		HttpSession session = req.getSession();

		boolean flag = session.isNew();

		System.out.println("session是否存在：" + flag);
		//session不存在的情况
		if (flag == false) {
			String phone = req.getParameter("phone");
			String password = req.getParameter("password");

//		如果值为空，跳转到登陆失败页面
			if (phone == null || "".equals(phone)) {

				//在请求中添加属性：错误原因
				req.setAttribute("errMsg", "账号为空");
				//获取转发对象
				req.getRequestDispatcher("pages/error.jsp").forward(req, resp);
				return;
			}
			if (password == null || "".equals(password)) {

				//在请求中添加属性：错误原因
				req.setAttribute("errMsg", "密码为空");
				req.getRequestDispatcher("pages/error.jsp").forward(req, resp);
				return;
			}

			//登录逻辑：
//			->数据库的手机号和密码与登录界面的一致
			UserLog userLog = new UserLog();
			UserInfo userInfo = userLog.queryByPhoneNum(phone);
			System.out.println(userInfo.toString());
			//判断账号是否存在
			if (userInfo.getPhone() == null) {
				req.setAttribute("errMsg", "账号不存在");
				req.getRequestDispatcher("pages/error.jsp").forward(req, resp);
				return;
			}
			//判断密码是否正确
			if (!password.equals(userInfo.getPassword())) {
				req.setAttribute("errMsg", "密码错误");
				req.getRequestDispatcher("pages/error.jsp").forward(req, resp);
				return;
			}


			//往session添加用户信息，所有会话中，都可以访问到
			session.setAttribute("userInfo", userInfo);

			//以上判断都没有进入，表示登陆成功，跳转到主页,展示所有用户信息
			try {
				List<UserInfo> userInfoList = userLog.queryAllUserInfo();
//			req.setAttribute("userList", userInfoList);
//			req.getRequestDispatcher("pages/main.jsp").forward(req, resp);
				//存放主页信息
				session.setAttribute("userList", userInfoList);
				resp.sendRedirect("pages/newMain.jsp");
			} catch (SQLException throwables) {
				req.setAttribute("errMsg", "查询异常");
				req.getRequestDispatcher("pages/error.jsp").forward(req, resp);
			}
		} else {
			//session存在的情况
			UserInfo userInfo = (UserInfo) session.getAttribute("userInfo");

			if (userInfo != null) {
				resp.sendRedirect("pages/login.jsp");
				return;
			}

			resp.sendRedirect("pages/newMain.jsp");
		}




	}
}
